import { FishEvent, UserStats } from '../types';

const STORAGE_KEYS = {
  EVENTS: 'fish_events',
  STATS: 'fish_stats'
};

export const StorageUtil = {
  // 事件相关
  getEvents(): FishEvent[] {
    const data = localStorage.getItem(STORAGE_KEYS.EVENTS);
    return data ? JSON.parse(data) : [];
  },

  saveEvents(events: FishEvent[]): void {
    localStorage.setItem(STORAGE_KEYS.EVENTS, JSON.stringify(events));
  },

  addEvent(event: FishEvent): void {
    const events = this.getEvents();
    events.unshift(event);
    this.saveEvents(events);
  },

  deleteEvent(eventId: string): void {
    const events = this.getEvents().filter(event => event.id !== eventId);
    this.saveEvents(events);
  },

  // 统计相关
  getStats(): UserStats {
    const data = localStorage.getItem(STORAGE_KEYS.STATS);
    return data ? JSON.parse(data) : {
      totalEvents: 0,
      totalDuration: 0,
      currentLevel: 0,
      levelProgress: 0,
      achievements: []
    };
  },

  saveStats(stats: UserStats): void {
    localStorage.setItem(STORAGE_KEYS.STATS, JSON.stringify(stats));
  },

  // 清除所有数据
  clearAllData(): void {
    localStorage.removeItem(STORAGE_KEYS.EVENTS);
    localStorage.removeItem(STORAGE_KEYS.STATS);
  }
};

export const DateUtil = {
  formatDate(timestamp: number): string {
    return new Date(timestamp).toLocaleDateString('zh-CN');
  },

  formatTime(timestamp: number): string {
    return new Date(timestamp).toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    });
  },

  formatDuration(minutes: number): string {
    if (minutes < 60) {
      return `${minutes}分钟`;
    }
    const hours = Math.floor(minutes / 60);
    const remainingMinutes = minutes % 60;
    return `${hours}小时${remainingMinutes > 0 ? remainingMinutes + '分钟' : ''}`;
  },

  isToday(timestamp: number): boolean {
    const today = new Date();
    const date = new Date(timestamp);
    return today.toDateString() === date.toDateString();
  },

  isThisWeek(timestamp: number): boolean {
    const today = new Date();
    const date = new Date(timestamp);
    const weekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
    return date >= weekAgo;
  },

  isThisMonth(timestamp: number): boolean {
    const today = new Date();
    const date = new Date(timestamp);
    return today.getMonth() === date.getMonth() && today.getFullYear() === date.getFullYear();
  }
};